package service

import (
	"context"
	"gomain/app/model"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
)

var Order = orderService{}

type orderService struct{}

func (s *orderService) List(page, limit int) ([]model.Order, int, error) {
	var orders []model.Order

	m := g.DB().Model("pos_orders")
	count, err := m.Count()
	if err != nil {
		return nil, 0, err
	}

	err = m.Page(page, limit).Scan(&orders)
	return orders, count, err
}

func (s *orderService) GetDetail(orderId int) (*model.Order, []model.OrderItem, error) {
	var order model.Order
	var items []model.OrderItem

	err := g.DB().Model("pos_orders").Where("id=?", orderId).Scan(&order)
	if err != nil {
		return nil, nil, err
	}

	err = g.DB().Model("pos_order_items").Where("order_id=?", orderId).Scan(&items)
	if err != nil {
		return nil, nil, err
	}

	return &order, items, nil
}

func (s *orderService) Create(order *model.Order, items []model.OrderItem) error {
	ctx := context.Background()
	return g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		// 插入订单
		res, err := tx.Model("pos_orders").Data(order).Insert()
		if err != nil {
			return err
		}

		orderId, err := res.LastInsertId()
		if err != nil {
			return err
		}

		// 插入订单明细
		for _, item := range items {
			item.OrderId = int(orderId)
			_, err = tx.Model("pos_order_items").Data(item).Insert()
			if err != nil {
				return err
			}
		}

		return nil
	})
}
